#!/usr/bin/env python3
import sys
import subprocess
import time
from typing import Dict, Callable

def print_menu() -> None:
    """显示主菜单"""
    print("=========================================================================")
    print("                               Agiros 编译工具集                           ")
    print("=========================================================================")
    print("1. 全自动下载&编译&安装（全量模式）    - 执行下载编译安装所有步骤")
    print("2. 全自动下载&编译&安装（增量模式）    - 执行下载和增量编译安装步骤")
    print("3. 全自动编译&安装（全量模式） - 执行全量编译安装步骤")
    print("4. 全自动编译&安装（增量模式） - 仅执行增量编译安装步骤")
    print("5. 源码下载          - 从gitee下载agiros源码")
    print("6. 创建编译工作空间  - 按照rpmbuild目录结构创建")
    print("7. 文件收集          - 复制tar、patch和spec文件")
    print("8. 生成编译顺序文件  - 输出agiros包的编译顺序")
    print("9. 安装三方依赖包    - 安装编译和运行时依赖")
    print("10. 编译rpm包         - 编译agiros自有包")
    print("11. 退出              - 退出程序")
    print("=========================================================================")

def run_download() -> None:
    """执行源码下载"""
    print("开始从gitee下载agiros源码...")
    start_time = time.time()
    try:
        #调用download脚本时增加update参数
        subprocess.run([sys.executable, "download.py", "--update"], check=True)
        duration = time.time() - start_time
        print(f"源码下载完成！耗时: {duration:.2f}秒")
    except subprocess.CalledProcessError as e:
        duration = time.time() - start_time
        print(f"源码下载失败: {e}，耗时: {duration:.2f}秒")
    except FileNotFoundError:
        duration = time.time() - start_time
        print(f"错误: 未找到download.py脚本，耗时: {duration:.2f}秒")

def run_create_workspace() -> None:
    """创建编译工作空间"""
    print("开始创建rpmbuild编译工作空间...")
    start_time = time.time()
    try:
        subprocess.run([sys.executable, "create.py", "--clean"], check=True)
        duration = time.time() - start_time
        print(f"编译工作空间创建完成！耗时: {duration:.2f}秒")
    except subprocess.CalledProcessError as e:
        duration = time.time() - start_time
        print(f"创建工作空间失败: {e}，耗时: {duration:.2f}秒")
    except FileNotFoundError:
        duration = time.time() - start_time
        print(f"错误: 未找到create.py脚本，耗时: {duration:.2f}秒")

def run_collect_files() -> None:
    """执行文件收集"""
    print("开始收集tar、patch和spec文件...")
    start_time = time.time()
    try:
        subprocess.run([sys.executable, "collect.py"], check=True)
        duration = time.time() - start_time
        print(f"文件收集完成！耗时: {duration:.2f}秒")
    except subprocess.CalledProcessError as e:
        duration = time.time() - start_time
        print(f"文件收集失败: {e}，耗时: {duration:.2f}秒")
    except FileNotFoundError:
        duration = time.time() - start_time
        print(f"错误: 未找到collect.py脚本，耗时: {duration:.2f}秒")

def run_gen_order() -> None:
    """生成编译顺序文件"""
    print("开始生成agiros包编译顺序...")
    start_time = time.time()
    try:
        subprocess.run([sys.executable, "genorder.py"], check=True)
        duration = time.time() - start_time
        print(f"编译顺序文件已生成: orderedspec.conf，耗时: {duration:.2f}秒")
    except subprocess.CalledProcessError as e:
        duration = time.time() - start_time
        print(f"生成编译顺序失败: {e}，耗时: {duration:.2f}秒")
    except FileNotFoundError:
        duration = time.time() - start_time
        print(f"错误: 未找到genorder.py脚本，耗时: {duration:.2f}秒")

def run_install_deps() -> None:
    """安装三方依赖包"""
    print("开始安装agiros编译和运行时依赖...")
    start_time = time.time()
    try:
        subprocess.run([sys.executable, "install3rd.py"], check=True)
        duration = time.time() - start_time
        print(f"三方依赖包安装完成！耗时: {duration:.2f}秒")
    except subprocess.CalledProcessError as e:
        duration = time.time() - start_time
        print(f"依赖安装失败: {e}，耗时: {duration:.2f}秒")
    except FileNotFoundError:
        duration = time.time() - start_time
        print(f"错误: 未找到install3rd.py脚本，耗时: {duration:.2f}秒")

def run_build_rpm() -> None:
    """增量编译rpm包"""
    print("开始编译agiros包...")
    start_time = time.time()
    try:
        subprocess.run([sys.executable, "build.py"], check=True)
        duration = time.time() - start_time
        print(f"rpm包编译完成！耗时: {duration:.2f}秒")
    except subprocess.CalledProcessError as e:
        duration = time.time() - start_time
        print(f"rpm包编译失败: {e}，耗时: {duration:.2f}秒")
    except FileNotFoundError:
        duration = time.time() - start_time
        print(f"错误: 未找到build.py脚本，耗时: {duration:.2f}秒")

def run_build_all_rpm() -> None:
    """全量编译rpm包"""
    print("开始编译agiros包...")
    start_time = time.time()
    try:
        subprocess.run([sys.executable, "build.py", "--all"], check=True)
        duration = time.time() - start_time
        print(f"rpm包编译完成！耗时: {duration:.2f}秒")
    except subprocess.CalledProcessError as e:
        duration = time.time() - start_time
        print(f"rpm包编译失败: {e}，耗时: {duration:.2f}秒")
    except FileNotFoundError:
        duration = time.time() - start_time
        print(f"错误: 未找到build.py脚本，耗时: {duration:.2f}秒")

def run_full_automatic_incremental() -> None:
    """全自动下载&编译&安装流程（增量模式）"""
    print("开始全自动下载&编译&安装流程（增量模式）...")
    total_start_time = time.time()
    total_duration = 0
    
    steps = [
        ("源码下载", run_download),
        ("安装三方依赖包", run_install_deps),
        ("编译rpm包", run_build_rpm)
    ]
    
    for step_name, step_func in steps:
        print(f"\n----- 开始{step_name} -----\n")
        step_start = time.time()
        try:
            step_func()
            step_duration = time.time() - step_start
            total_duration += step_duration
            print(f"----- {step_name}成功，耗时: {step_duration:.2f}秒 -----\n")
        except Exception as e:
            step_duration = time.time() - step_start
            total_duration += step_duration
            print(f"----- {step_name}失败: {str(e)}，耗时: {step_duration:.2f}秒 -----\n")
            if step_name != "安装三方依赖包":
                print("流程终止，因为非三方依赖包步骤失败")
                break
            print("继续执行后续步骤...")
    
    total_time = time.time() - total_start_time
    print(f"\n全自动下载&编译&安装流程（增量模式）已完成！总耗时: {total_time:.2f}秒")


def run_full_automatic() -> None:
    """全自动编译&安装流程"""
    print("开始全自动编译&安装流程...")
    total_start_time = time.time()
    total_duration = 0
    
    steps = [
        ("源码下载", run_download),
        ("创建编译工作空间", run_create_workspace),
        ("文件收集", run_collect_files),
        ("生成编译顺序文件", run_gen_order),
        ("安装三方依赖包", run_install_deps),
        ("编译rpm包", run_build_all_rpm)
    ]
    
    for step_name, step_func in steps:
        print(f"\n----- 开始{step_name} -----\n")
        step_start = time.time()
        try:
            step_func()
            step_duration = time.time() - step_start
            total_duration += step_duration
            print(f"----- {step_name}成功，耗时: {step_duration:.2f}秒 -----\n")
        except Exception as e:
            step_duration = time.time() - step_start
            total_duration += step_duration
            print(f"----- {step_name}失败: {str(e)}，耗时: {step_duration:.2f}秒 -----\n")
            if step_name != "安装三方依赖包":
                print("流程终止，因为非三方依赖包步骤失败")
                break
            print("继续执行后续步骤...")
    
    total_time = time.time() - total_start_time
    print(f"\n全自动编译&安装流程已完成！总耗时: {total_time:.2f}秒")
 

def run_full_automatic_without_download_incremental() -> None:
    """全自动编译&安装流程（增量模式）"""
    print("开始全自动编译&安装流程（增量模式）...")
    total_start_time = time.time()
    total_duration = 0
    
    steps = [
        ("安装三方依赖包", run_install_deps),
        ("编译rpm包", run_build_rpm)
    ]
    
    for step_name, step_func in steps:
        print(f"\n----- 开始{step_name} -----\n")
        step_start = time.time()
        try:
            step_func()
            step_duration = time.time() - step_start
            total_duration += step_duration
            print(f"----- {step_name}成功，耗时: {step_duration:.2f}秒 -----\n")
        except Exception as e:
            step_duration = time.time() - step_start
            total_duration += step_duration
            print(f"----- {step_name}失败: {str(e)}，耗时: {step_duration:.2f}秒 -----\n")
            if step_name != "安装三方依赖包":
                print("流程终止，因为非三方依赖包步骤失败")
                break
            print("继续执行后续步骤...")
    
    total_time = time.time() - total_start_time
    print(f"\n全自动编译&安装流程（增量模式）已完成！总耗时: {total_time:.2f}秒")
 

def run_full_automatic_without_download() -> None:
    """全自动编译&安装流程（不含源码下载）"""
    print("开始全自动编译&安装流程（不含源码下载）...")
    total_start_time = time.time()
    total_duration = 0
    
    steps = [
        ("创建编译工作空间", run_create_workspace),
        ("文件收集", run_collect_files),
        ("生成编译顺序文件", run_gen_order),
        ("安装三方依赖包", run_install_deps),
        ("编译rpm包", run_build_all_rpm)
    ]
    
    for step_name, step_func in steps:
        print(f"\n----- 开始{step_name} -----\n")
        step_start = time.time()
        try:
            step_func()
            step_duration = time.time() - step_start
            total_duration += step_duration
            print(f"----- {step_name}成功，耗时: {step_duration:.2f}秒 -----\n")
        except Exception as e:
            step_duration = time.time() - step_start
            total_duration += step_duration
            print(f"----- {step_name}失败: {str(e)}，耗时: {step_duration:.2f}秒 -----\n")
            if step_name != "安装三方依赖包":
                print("流程终止，因为非三方依赖包步骤失败")
                break
            print("继续执行后续步骤...")
    
    total_time = time.time() - total_start_time
    print(f"\n全自动编译&安装流程（不含源码下载）已完成！总耗时: {total_time:.2f}秒")
 

def main() -> None:
    """主函数"""
    # 菜单选项与函数映射
    menu_actions: Dict[str, Callable[[], None]] = {
        '1': run_full_automatic,
        '2': run_full_automatic_incremental,
        '3': run_full_automatic_without_download,
        '4': run_full_automatic_without_download_incremental,
        '5': run_download,
        '6': run_create_workspace,
        '7': run_collect_files,
        '8': run_gen_order,
        '9': run_install_deps,
        '10': run_build_rpm
    }

    while True:
        print_menu()
        choice = input("请输入选项 (1-11): ").strip()

        if choice == '11':
            print("感谢使用Agiros编译工具集，再见！")
            break
        elif choice in menu_actions:
            try:
                menu_actions[choice]()
            except Exception as e:
                print(f"执行操作时发生错误: {str(e)}")
        else:
            print("无效的选项，请输入1-11之间的数字")

        # 操作完成后暂停，等待用户按Enter继续
        input("按Enter键继续...")
        # 清屏（跨平台兼容）
        #subprocess.run('cls' if sys.platform.startswith('win') else 'clear', shell=True)

if __name__ == "__main__":
    main()